import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import command from '../command/command.js'
import puppeteer from '../../../lib/puppeteer/puppeteer.js'



export class covid19Real extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: '疫情信息查询',
            /** 功能描述 */
            dsc: '获取疫情信息（腾讯数据）',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 1006,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: '^#*(.*)疫情$',
                    /** 执行方法 */
                    fnc: 'covid19Real'
                }
            ]
        })
    }

    /**
     * 
     * @param e oicq传递的事件参数e
     */
    async covid19Real(e) {
        let emsg = e.msg.replace(/#|＃|疫情/g, "");
        //https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5
        let url = "https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=diseaseh5Shelf"; //疫情接口地址
        let response = await fetch(url); //调用接口获取数据
        let res = await response.json(); //结果json字符串转对象

        if (res.ret != 0) {
            return true;
        }

        let data = res.data;

        let areaname = "";
        let areanamebd = "";
        let time = data.diseaseh5Shelf.lastUpdateTime;
        let nowConfirm = "";    //现有确诊
        let confirmtoday = "";  //新增本土
        let wzz = "";
        let confirm = "";       //累计确诊
        let heal = "";
        let dead = "";
        let adCode = "";

        let areaTree = data.diseaseh5Shelf.areaTree;
        let children = areaTree[0].children;
        for (const key in children) {

            if (!emsg || emsg.length <= 0) {
                areaname = "中国"
                areanamebd = "国内";
                nowConfirm = data.diseaseh5Shelf.chinaTotal.nowConfirm;
                confirmtoday = data.diseaseh5Shelf.chinaAdd.confirm;
                wzz = data.diseaseh5Shelf.chinaAdd.noInfect;
                confirm = data.diseaseh5Shelf.chinaTotal.confirm;
                heal = data.diseaseh5Shelf.chinaTotal.heal;
                dead = data.diseaseh5Shelf.chinaTotal.dead;
                break;
            }

            let nowres = children[key];
            let areNameTemp = nowres.name;
            if (nowres.name.indexOf(emsg) != -1) { //找省
                areaname= children[key].name;
                areanamebd = children[key].name;
                adCode = children[key].adcode;
                confirmtoday = children[key].today.confirm;
                wzz = children[key].today.wzz_add;

                nowConfirm = children[key].total.nowConfirm;
                confirm = children[key].total.confirm;
                heal = children[key].total.heal;
                dead = children[key].total.dead;
                break;
            }
            else { //找市
                let newCity = nowres.children;
                for (const key in newCity) {
                    if (newCity[key].name.indexOf(emsg) != -1) {

                        if (areNameTemp) {
                            areaname += `【${areNameTemp}】 `;
                            areanamebd += areNameTemp;
                        }
                        areaname += newCity[key].name;
                        areanamebd += newCity[key].name;
                        adCode = newCity[key].adcode;
                        confirmtoday = newCity[key].today.confirm;
                        wzz = newCity[key].total.wzz;

                        nowConfirm = newCity[key].total.nowConfirm;
                        confirm = newCity[key].total.confirm;
                        heal = newCity[key].total.heal;
                        dead = newCity[key].total.dead;

                        break;
                    }
                }

            }
        }

        let chartName1 = "";
        let chartName2 = "";
        let chartData1 = [];
        let chartData2 = [];

        if (!adCode) {
            let url = "https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=chinaDayListNew,chinaDayAddListNew&limit=30"; //疫情接口地址
            let response = await fetch(url); //调用接口获取数据
            let res = await response.json(); //结果json字符串转对象

            if (res.ret != 0) {
                return true;
            }

            for (const key in res.data.chinaDayAddListNew) {
                chartData1.push({
                    date: res.data.chinaDayAddListNew[key].date.toString(),
                    value: res.data.chinaDayAddListNew[key].localConfirmadd
                })
            }
            chartName1 = "全国新增本土确诊趋势";

            for (const key in res.data.chinaDayListNew) {
                chartData2.push({
                    date: res.data.chinaDayListNew[key].date.toString(),
                    value: res.data.chinaDayListNew[key].localConfirm
                })
            }
            chartName2 = "全国现有本土确诊趋势";

        }
        else {
            // console.log(adCode);
            let url = `https://api.inews.qq.com/newsqa/v1/query/pubished/daily/list?adCode=${adCode}&limit=30`; //疫情接口地址
            let response = await fetch(url); //调用接口获取数据
            let res = await response.json(); //结果json字符串转对象
            if (res.ret != 0 || !res.data) {
                return true;
            }
            for (const key in res.data) {
                chartData1.push({
                    date: res.data[key].date.toString(),
                    value: (res.data[key].all_local_confirm_add || res.data[key].all_local_confirm_add == 0) ? res.data[key].all_local_confirm_add : res.data[key].today_confirm_add
                })
            }
            chartName1 = `${areaname}  新增本土确诊趋势`;

            for (const key in res.data) {
                chartData2.push({
                    date: res.data[key].date.toString(),
                    value: (res.data[key].wzz_add || res.data[key].wzz_add == 0) ? res.data[key].wzz_add : res.data[key].today_wzz_add
                })
            }
            chartName2 = `${areaname}  新增无症状趋势`;
        }

        chartData1 = JSON.stringify(chartData1);
        chartData2 = JSON.stringify(chartData2);


        let bdevents = [];
        let bdurl = `https://opendata.baidu.com/data/inner?tn=reserved_all_res_tn&dspName=iphone&from_sf=1&dsp=iphone&resource_id=28565&alr=1&query=${areanamebd}新型肺炎最新动态`; //疫情接口地址
        let bdresponse = await fetch(bdurl); //调用接口获取数据
        let bdres = await bdresponse.json(); //结果json字符串转对象
        console.log(bdurl);
        if (bdres.Result.length > 0) {
            bdevents = bdres.Result[0].items_v2[0].aladdin_res.DisplayData.result.items;
            // console.log(res.Result[0].items_v2[0].aladdin_res.DisplayData.result.items);
            // console.log('res.Result.length: ',res.Result.length);
            // console.log('res.Result.items_v2.length: ',res.Result.items_v2.length);
            // console.log('res.Result[0].items_v2[0].aladdin_res.DisplayData.result.items.length: ',res.Result[0].items_v2[0].aladdin_res.DisplayData.result.items.length);

            for (const key in bdevents) {
                bdevents[key].eventTime = new Date(bdevents[key].eventTime * 1000).toLocaleString();
            }

            bdevents = bdevents.slice(0, 5);
        }

        let imgdata = await command.getData("covid19Real",
            {
                areaname,
                time,
                nowConfirm,
                confirmtoday,
                wzz,
                confirm,
                heal,
                dead,
                chartName1,
                chartName2,
                chartData1,
                chartData2,
                bdevents
            });
        /** 生成图片 */
        let img = await puppeteer.screenshot('covid19Real', imgdata);
        if (img && areaname) await this.reply(img);

    }
}
